import React, { Children, useEffect, useRef, useState } from 'react';
import { CourseDetail } from '@/pages/pc/components';
import { WorksItem } from '@/pages/pc/components/Works';
import { Tabs, Select, Spin, Skeleton, Typography, Upload, message, Modal } from 'antd';
import classNames from 'classnames';
import { Link, useHistory, useRequest } from 'umi';
import { mockData } from '@/utils/mock';
import styles from './index.less';
import PreviewImg from '@/components/PreviewImg';
import Pagination from '@/pages/pc/components/Pagination';
import VideoPlayerModal from '../components/VideoPlayer';
import InvoiceModal from '../components/InvoiceModal';
import Slider from 'react-slick';
import 'slick-carousel/slick/slick.css';
import 'slick-carousel/slick/slick-theme.css';
import request from '@/utils/request';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';
import type { UploadChangeParam } from 'antd/es/upload';
import { allGet, allPost } from '@/services/pc';
import { downLoad } from '@/utils';
import Empty from '@/pages/pc/components/Empty';
import moment from 'moment';
import WorkDetailModal, { WorkDetailModalRef } from '@/pages/pc/components/WorkDetailModal';
const { TabPane } = Tabs;
const { Paragraph } = Typography;

const transformReward = (data = []) => {
  return [
    {
      type: 'S',
      text:
        data?.[4]?.[1] != 0 || data?.[4]?.[2] != 0
          ? data?.[4]?.[1] != 0
            ? `S:${data?.[4]?.[1]}元RMB`
            : `S:${data?.[4]?.[2]}点CG券`
          : '',
    },
    {
      type: 'A+',
      text:
        data?.[3]?.[1] != 0 || data?.[3]?.[2] != 0
          ? data?.[3]?.[1] != 0
            ? `A+:${data?.[3]?.[1]}元RMB`
            : `A+:${data?.[3]?.[2]}点CG券`
          : '',
    },
    {
      type: 'A',
      text:
        data?.[2]?.[1] != 0 || data?.[2]?.[2] != 0
          ? data?.[2]?.[1] != 0
            ? `A:${data?.[2]?.[1]}元RMB`
            : `A:${data?.[2]?.[2]}点CG券`
          : '',
    },
    {
      type: 'B',
      text:
        data?.[1]?.[1] != 0 || data?.[1]?.[2] != 0
          ? data?.[1]?.[1] != 0
            ? `B:${data?.[1]?.[1]}元RMB`
            : `B:${data?.[1]?.[2]}点CG券`
          : '',
    },
  ];
};

interface CoursesListProps {
  onChange?: (id) => void;
  data: any[];
  classId: any;
}
const CoursesList: React.FC<CoursesListProps> = ({ onChange, data, classId }) => {
  console.log(classId, 'classId');
  const settings = {
    dots: false,
    infinite: false,
    slidesToShow: 6,
    slidesToScroll: 6,
    vertical: true,
    arrows: false,
    verticalSwiping: true,
    swipeToSlide: true,
    beforeChange: function (currentSlide, nextSlide) {
      setCurrentSlide(nextSlide * 2);
      console.log('before change', currentSlide, nextSlide);
    },
    afterChange: function (currentSlide) {
      console.log('after change', currentSlide);
    },
  };

  const [currentSlide, setCurrentSlide] = useState(0);

  const sliderRef = useRef<any>();
  const handlePrev = () => {
    if (currentSlide === 0) return;
    sliderRef.current?.slickPrev();
  };
  const handleNext = () => {
    if (currentSlide >= data.length) return;
    sliderRef.current?.slickNext();
  };

  const handleChange = (classid) => {
    window.scrollTo({
      left: 0,
      top: 0,
      // behavior: 'smooth'//或'auto'
    });
    onChange?.(classid);
  };

  const rendetItem = (item, index) => {
    return (
      <div
        key={item.classid}
        className={classNames(styles.item, { [styles.actived]: classId === item.classid })}
        onClick={() => handleChange(item.classid)}
      >
        <div className={styles.content} style={{ backgroundImage: `url(${item.pic})` }}>
          {index === 0 && <span className={styles.last}>上次学习</span>}
          <div className={styles.over}>
            <div className={styles.title}>{item.classname}</div>
          </div>
        </div>
      </div>
    );
  };
  return (
    <div className={styles.coursesList}>
      <div className={styles.header}>我的课程</div>
      {data.map((item, index) => rendetItem(item, index))}
    </div>
  );
};

const scoresMap = { 1: 'B', 2: 'A', 3: 'A+', 4: 'S' };
interface ScoresProps {
  busywork: any;
  score?: 1 | 2 | 3 | 4;
  /**
   * 1 未上传
   * 2 已上传未评分
   * 3 已评分
   */
  status: 1 | 2 | 3;
  reward;
}

const workDate = (dateline) => {
  if (!dateline) return '-';
  // 将时间戳转换为毫秒
  const timestamp = parseInt(dateline, 10) * 1000;

  // 使用 moment.js 处理时间
  const momentTime = moment(timestamp);
  const now = moment();

  // 计算时间差
  const diffSeconds = now.diff(momentTime, 'seconds');
  const diffMinutes = now.diff(momentTime, 'minutes');
  const diffHours = now.diff(momentTime, 'hours');

  // 根据时间差选择显示格式
  let displayTime;
  if (diffSeconds < 60) {
    displayTime = `${diffSeconds}秒前`;
  } else if (diffMinutes < 60) {
    displayTime = `${diffMinutes}分钟前`;
  } else if (diffHours < 24) {
    displayTime = `${diffHours}小时前`;
  } else {
    displayTime = momentTime.format('YYYY-MM-DD');
  }
  return displayTime;
};

const labaText = {
  1: '加油，你可以更棒！',
  2: '小有成就，前路坦阔 ',
  3: ' 封神就在前方',
  4: ' 一览众山小',
};
const Scores: React.FC<ScoresProps> = ({ score, busywork, status, reward }) => {
  const [index, setIndex] = useState(score ?? 0);
  const [open, setOpen] = useState(false);
  const [works, setWorks] = useState<any[]>([]);
  const disabled = false;
  const handleClick = (index) => {
    return;
  };
  const workDetailModalRef = useRef<WorkDetailModalRef>(null);
  const handleWorkClick = (bid) => {
    workDetailModalRef.current?.show({
      ids: [bid],
      currentId: bid,
    });
    // VideoPlayerModal.showStar({
    //   data:
    //     props?.works?.data?.list?.map((item) => ({ ...item, url: item.video || item.pic })) || [],
    //   defaultIndex: index,
    // });
  };

  const handleOpenWorkList = async () => {
    setOpen(true);
    const response = await allGet({
      params: {
        mod: 'busywork',
        do: 'my',
        perpage: 9999,
        page: 1,
        lid: busywork.lid,
        version: 'pc1.0',
      },
    });
    setWorks(response?.data?.list || []);
  };
  const renderContent = () => {
    if (!busywork) {
      return <div className={styles.zanweishangchuang}>暂未上传作业</div>;
    }
    return (
      <>
        <div className={styles.processtop}>
          <div className={styles.processtopleft}>
            <div className={styles.version}>版本{busywork.current}</div>
            <div className={styles.workInfo}>
              <img
                src={busywork.thumb}
                className={styles.workimg}
                alt=""
                onClick={() => handleWorkClick(busywork?.bid)}
              />
              <div className={styles.workInfoRight}>
                <div className={styles.workInfoTitle}>{busywork.subject}</div>
                <div className={styles.workInfoDate}>{workDate(busywork.dateline)}</div>
              </div>
            </div>
          </div>
          <div className={styles.processtopright}>
            {!busywork.score ? (
              <div className={styles.weipingfeng}>老师还未批改</div>
            ) : (
              <>
                <div className={styles.jiangliWrapper}>
                  <div className={styles.row}>
                    <div className={styles.key}>评分：</div>
                    {score ? scoresMap[score] : '-'}
                  </div>
                  <div className={styles.row}>
                    <div className={styles.key}>奖励：</div>
                    {reward || '-'}
                  </div>
                </div>
                <div className={styles.line} />
                <div className={classNames(styles.yifafang, { [styles.disabled]: !reward })}>
                  {reward ? '奖励已发放' : '无奖'}
                </div>
              </>
            )}
          </div>
        </div>
        <div className={classNames(styles['process-wrapper'], styles[`score-${index}`])}>
          <div className={styles['score-wrapper']}>
            <div
              className={classNames(styles['score-item'], styles.b)}
              onClick={() => handleClick(1)}
            >
              <i className={styles.icon} />
            </div>
            <div
              className={classNames(styles['score-item'], styles.a)}
              onClick={() => handleClick(2)}
            >
              <i className={styles.icon} />
            </div>
            <div
              className={classNames(styles['score-item'], styles.as)}
              onClick={() => handleClick(3)}
            >
              <i className={styles.icon} />
            </div>
            <div
              className={classNames(styles['score-item'], styles.s)}
              onClick={() => handleClick(4)}
            >
              <i className={styles.icon} />
            </div>
          </div>
          <i className={classNames(styles.opacitYprocess, styles[index])} />
          <i className={classNames(styles.process, styles[`process-${index}`])} />
        </div>
        <div className={classNames(styles.info, { [styles.actived]: busywork.score })}>
          <div className={styles.labaWrapper}>
            <div className={styles.icon} />
            <div className={styles.text}>{labaText[busywork?.score] || '-'}</div>
          </div>
          <div className={styles.lishi} onClick={handleOpenWorkList}>
            <div className={styles.text}>查看该作业历史记录</div>
            <div className={styles.icon} />
          </div>
        </div>
      </>
    );
  };
  return (
    <div className={styles.scores}>
      {renderContent()}
      <WorkDetailModal ref={workDetailModalRef} />
      <Modal
        open={open}
        destroyOnClose
        maskClosable
        onCancel={() => setOpen(false)}
        className={styles.workHistory}
        title="作业历史"
        width={596}
        centered
        footer={null}
      >
        <div className={styles.workList}>
          {works.map((item) => {
            return (
              <div className={styles.item} key={item.bid}>
                <div className={styles.left}>
                  <div className={styles.version}>版本{item.current}</div>
                  <div className={styles.info}>
                    <img
                      className={styles.img}
                      src={item.thumb}
                      onClick={() => handleWorkClick(item.bid)}
                    />
                    <div className={styles.inforight}>
                      <div className={styles.title} onClick={() => handleWorkClick(item.bid)}>
                        {item.subject}
                      </div>
                      <div className={styles.date}>{workDate(item.dateline)}</div>
                    </div>
                  </div>
                </div>
                <div className={styles.right}>
                  {!item.score ? (
                    <div className={classNames(styles.yifafang, styles.disabled)}>未批改</div>
                  ) : (
                    <>
                      <div className={styles.jiangliWrapper}>
                        <div className={styles.row}>
                          <div className={styles.key}>评分：</div>
                          {item.score ? scoresMap[item.score] : '-'}
                        </div>
                        <div className={styles.row}>
                          <div className={styles.key}>奖励：</div>
                          {item.reward || '-'}
                        </div>
                      </div>
                      <div
                        className={classNames(styles.yifafang, { [styles.disabled]: !item.reward })}
                      >
                        {item.reward ? '奖励已发放' : '无奖'}
                      </div>
                    </>
                  )}
                </div>
              </div>
            );
          })}
        </div>
      </Modal>
    </div>
  );
};

const Requirements = ({ text }) => {
  const [ellipsis, setEllipsis] = useState(true);
  /**
   * 点击document快速关闭弹窗
   */
  useEffect(() => {
    const close = () => {
      setEllipsis(true);
    };
    document.addEventListener('click', close);
    return () => {
      document.removeEventListener('click', close);
    };
  }, []);
  // const article = `1、把做作业当作自己的事情，把学习看作“学习知识、掌握本领的快乐享受”，积极主动地做作业
  //   2、不要经老师、父母催促、监督提醒。要独立完成作业。做作业时，不要老师、家长在旁边陪伴、辑的空间啊还是诋毁还 3、不要经老师、父母催促、监督提醒。要独立完成作业。做作业时，不要老师、家长在旁边陪伴、辑的空间啊还是诋毁还`
  return (
    <div className={styles.content}>
      {' '}
      <Paragraph
        onClick={(e) => e?.stopPropagation()}
        className={classNames(styles.paragraph, { [styles.actived]: !ellipsis })}
        key={String(ellipsis)}
        ellipsis={
          ellipsis
            ? {
                rows: 3,
                expandable: true,
                onEllipsis: (ellipsis) => {
                  console.log('Ellipsis changed:', ellipsis);
                },
                symbol: '展开',
                onExpand: (e) => {
                  e.stopPropagation();
                  console.log(1111);
                  setEllipsis(false);
                },
              }
            : false
        }
      >
        {text}
      </Paragraph>
    </div>
  );
};
const isImg = (name) => {
  const arr = ['.jpg', '.jpeg', '.png', '.gif'];
  const index = name.lastIndexOf('.');
  const suffix = name.slice(index);
  return arr.includes(suffix);
};
const isVideo = (name) => {
  const arr = ['.avi', '.mp4', '.mov'];
  const index = name?.lastIndexOf('.');
  const suffix = name?.slice(index);
  return arr.includes(suffix);
};

// 上传作业
interface UploadWorkProps {
  data?: Record<string, any>;
  OSSData: Record<string, any>;
  onChange?: () => void;
}
const UploadWork: React.FC<any> = ({
  onChange = (fileList) => {},
  children,
  data = {},
  OSSData,
}) => {
  // const [loading, setLoading] = useState(false);

  // const [url, setUrl] = useState<string>();

  // const getExtraData = file => {
  //   return {
  //     ...data,
  //     key: file.key,
  //     OSSAccessKeyId: OSSData.accessId,
  //     policy: OSSData.policy,
  //     Signature: OSSData.signature,
  //   };
  // };
  // const beforeUpload = async (file) => {

  //   const isimg = isImg(file.name)
  //   const isvideo = isVideo(file.name);
  //   // 格式不符合
  //   if (!isimg && !isvideo) {
  //     message.error('图片仅支持 jpg/png/gif 格式, 视频仅支持 avi/mp4/mov 格式');
  //     return Upload.LIST_IGNORE;
  //   }
  //   const index = file.name.lastIndexOf('.');
  //   const suffix = file.name.slice(index);
  //   const name = file.name.slice(0, index);
  //   const filename = name + '-' + Date.now() + suffix;
  //   file.key = OSSData.dir + filename;
  //   file.url = OSSData.host + '/' + OSSData.dir + filename;

  //   return file;
  // };
  // const handleChange: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
  //   if (info.file.status === 'uploading') {
  //     setLoading(true);
  //     return;
  //   }
  //   if (info.file.status === 'done') {
  //     setUrl(info.file.url);
  //     setLoading(false);
  //     onChange(info.file);
  //   }
  //   if (info.file.status === 'error') {
  //     message.error('上传失败');
  //     setLoading(false);
  //   }
  // };

  // const uploadButton = (
  //   <Spin spinning={loading} className={styles.loading} >

  //   </Spin>
  // );

  // const props = {
  //   // action: 'https://www.mocky.io/v2/5cc8019d300000980a055e76' ||  OSSData.host,
  //   action: OSSData.host,
  //   data: getExtraData,
  //   listType: "picture-card",
  //   className: styles.uploadUploadWork,
  //   showUploadList: false,
  //   beforeUpload: beforeUpload,
  //   onChange: handleChange,
  //   disabled: loading,
  // }
  return <>{children}</>;
};

const Catalogue = ({ classId, chaptersData }) => {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<any[]>([]);
  const history = useHistory();
  const index = useRef(1);
  const transformChapters = (chapters) => {
    let _index = 1;
    let newData: any[] = [];
    chapters.forEach((item) => {
      if (Array.isArray(item.children) && item.children.length > 0) {
        item.children?.forEach?.((item) => {
          item._index = _index++;
        });
        const children = item.children.filter((item) => item.allowbusywork == 1);
        if (children.length > 0) {
          if (item.cid === 0) {
            item.name = '其他';
          }
          newData = [...newData, { ...item, _type: 'chapter' }, ...children];
        }
      }
    });
    console.log(newData, 'newData');
    index.current = 1;
    setData(newData);
  };
  const getData = async () => {
    setLoading(true);
    // const response = await allGet({
    //   params: { mod: 'user', do: 'learn', classid: classId, version: 'pc1.0' },
    // });
    if (chaptersData && Array.isArray(chaptersData)) {
      transformChapters(chaptersData);
    } else {
      setData([]);
    }
    setLoading(false);
  };

  useEffect(() => {
    getData();
  }, [chaptersData, classId]);

  const handleShowWrok = (item) => {
    VideoPlayerModal.showList({
      data: [{ url: item?.busywork?.video || item?.busywork?.pic }],
    });
  };
  const [OSSData, setOssData] = useState<Record<string, any>>({});
  const init = async () => {
    // const res = await request('/api/oss-signature', { method: 'GET' });
    // if (res.success && res.data) {
    //   setOssData(res.data);
    // }
  };

  // useEffect(() => {
  //   init();
  // }, []);

  const goUploadWord = (item) => {
    const busywork = item.busywork;
    const hasScore = busywork && busywork.score && parseInt(busywork.score) > 0;

    // 有评分的作业只能重新上传，不能回填原先的作业
    if (hasScore) {
      return history.push(`/center/upload/work?lid=${item.lid}&classid=${item.classid}`);
    }

    if (item?.busywork?.bid) {
      history.push(
        `/center/upload/work?lid=${item.lid}&bid=${item?.busywork?.bid}&classid=${item.classid}`,
      );
    } else {
      history.push(`/center/upload/work?lid=${item.lid}&classid=${item.classid}`);
    }
  };
  const renderUploadStatus = (item) => {
    const busywork = item.busywork;
    const hasScore = busywork && busywork.score && parseInt(busywork.score) > 0;

    if (item._type === 'chapter') return null;
    if (item.busywork) {
      return (
        <>
          <div className={classNames(styles.button)} onClick={() => goUploadWord(item)}>
            {hasScore ? '重新提交' : '编辑作业'}
          </div>
          {/* <div className={styles.uploadSuccess} onClick={() => handleShowWrok(item)}>
            上传成功，查看
          </div> */}
        </>
      );
    }
    return (
      <div className={classNames(styles.button)} onClick={() => goUploadWord(item)}>
        上传作业
      </div>
    );
  };

  return (
    <section className={styles.catalogue}>
      <div className={styles.sectionTitle}>课程作业</div>
      <div className={styles.sectionBody}>
        {loading === true ? null : data.length <= 0 ? (
          <div className={styles.emptynew}>该课程暂未发布作业</div>
        ) : (
          data.map((item) => {
            const isChapter = item._type === 'chapter';
            const busywork = item.busywork;
            const reward = transformReward(item?.reward)
              .filter((item) => item.text)
              .map((item) => item.text);
            let scoreStatus: any = 1;
            // 上传了没评分
            if (busywork && busywork.score && parseInt(busywork.score) === 0) {
              scoreStatus = 2;
            }
            // 上传了有评分
            if (busywork && busywork.score && parseInt(busywork.score) > 0) {
              scoreStatus = 3;
            }
            console.log(scoreStatus, 'scoreStatus');
            return (
              <div
                key={item.lid || item.cid}
                className={classNames(styles.item, { [styles.chapter]: isChapter })}
              >
                <div className={styles.header}>
                  {isChapter ? '' : item._index} {item.name}
                  {renderUploadStatus(item)}
                </div>
                {!isChapter && (
                  <div className={styles.body}>
                    <div className={styles.left}>
                      {reward.length > 0 && (
                        <>
                          <div className={styles.title}>作业奖励：</div>
                          <div className={styles.jiangli}>{reward.join('、')}</div>
                        </>
                      )}
                      <div className={styles.title}>作业要求：</div>
                      {/* {item.busyworkrequest || '暂无'} */}
                      <Requirements text={item.busyworkrequest || '暂无'} />
                    </div>
                    <div className={styles.right}>
                      <Scores
                        busywork={busywork}
                        score={busywork?.score}
                        status={scoreStatus}
                        reward={busywork?.reward}
                      />
                    </div>
                  </div>
                )}
              </div>
            );
          })
        )}

        {/* <div className={classNames(styles.item, styles.chapter)}>
        <div className={styles.header}>
          第二章  对软件的整体认识和界面的讲解
          <UploadWork OSSData={OSSData}>
            <div className={classNames(styles.button)}>
              重新上传
            </div>
          </UploadWork>
          <div className={styles.uploadSuccess} onClick={() => handleShowVideo(1)}>
            上传成功，查看
            <i className={styles.icon} />
          </div>
        </div>
        <div className={styles.body}>
          <div className={styles.left}>
            <div className={styles.title}>作业要求：</div>
            <Requirements />
          </div>
          <i className={styles.line} />
          <div className={styles.right}>
            <Scores score={4} status={3} />
          </div>
        </div>
      </div>
      <div className={classNames(styles.item)}>
        <div className={styles.header}>5 进阶案例：吉祥物IP的建模与商业计划书
          <UploadWork OSSData={OSSData}>
            <div className={classNames(styles.button, styles.primary)}>
              上传作业
            </div>
          </UploadWork>
        </div>
        <div className={styles.body}>
          <div className={styles.left}>
            <div className={styles.title}>作业要求：</div>
            <Requirements />
          </div>
          <i className={styles.line} />
          <div className={styles.right}>
            <Scores status={1} />
          </div>
        </div>
      </div>
      <div className={classNames(styles.item)}>
        <div className={styles.header}>5 进阶案例：吉祥物IP的建模与商业计划书
          <UploadWork OSSData={OSSData}>
            <div className={classNames(styles.button, styles.primary)}>
              上传作业
            </div>
          </UploadWork>
        </div>
        <div className={styles.body}>
          <div className={styles.left}>
            <div className={styles.title}>作业要求：</div>
            <Requirements />
          </div>
          <i className={styles.line} />
          <div className={styles.right}>
            <Scores status={2} />
          </div>
        </div>
      </div> */}
      </div>
    </section>
  );
};
// 课程
const Courses = ({ classid }) => {
  const [loading, setLoading] = useState<boolean>();
  const [detailLoading, setdDetailLoading] = useState<boolean>(true);
  const [classes, setClasses] = useState<any[]>([]);
  const [classId, setClassid] = useState(classid);
  const [detail, setDetail] = useState<any>({});
  const [chaptersData, setChaptersData] = useState();

  useEffect(() => {
    getData();
  }, []);

  const getClassDetail = async () => {
    setdDetailLoading(false);
    if (!classId) return;
    setdDetailLoading(true);
    const [response] = [
      // await allGet({ params: { mod: 'course', do: 'detail', classid: classId, version: 'pc1.0' } }),
      await allGet({ params: { mod: 'user', do: 'learn', classid: classId, version: 'pc1.0' } }),
    ];
    if (response.success && response.data?.course) {
      const data = response.data?.course;
      // if (response2.data?.course?.downfile) {
      //   data.downfile = response2.data?.course?.downfile;
      // }
      setDetail(data);
      setChaptersData(response?.data?.chapters || []);
      console.log(classId, 'setDetail');
    }
    setdDetailLoading(false);
  };
  const classIdRef = useRef();
  useEffect(() => {
    // if (classId === classIdRef.current) return;
    // classIdRef.current = classId;
    getClassDetail();
  }, [classId]);
  const getData = async () => {
    setLoading(true);
    const response = await allGet({
      params: { mod: 'user', do: 'payed', version: 'pc1.0', page: 1, perpage: 99999 },
    });
    if (
      response.success &&
      Array.isArray(response?.data?.list) &&
      response?.data?.list?.length > 0
    ) {
      setClasses(response?.data?.list);
      const item = response.data.list[0] || {};
      if (!classId) {
        setClassid(item.classid);
      }
    }
    setLoading(false);
  };

  const handleChangeClass = (classId) => {
    if (detailLoading) return;
    setClassid(classId);
  };
  const courseDetailType = () => {
    if (detail?.bookprice > 0 && moment(detail?.bookdead, 'X').isSameOrAfter(moment())) {
      return 2;
    }
    if (detail.secskills?.secskillprice) {
      return 1;
    }
    if (detail.type == 8) {
      return 2;
    }
    return 3;
  };
  return (
    <div className={styles.courses}>
      {loading ? null : classes.length <= 0 ? (
        <Empty />
      ) : (
        <>
          <div className={styles.left}>
            <Spin spinning={detailLoading}>
              <CourseDetail
                className={styles.courseDetail}
                data={detail}
                classId={classId}
                type={courseDetailType()}
                role={3}
                onClick={() => window.open(`/center/courses/detail/${classId}`)}
              >
                <Catalogue classId={classId} chaptersData={chaptersData} />
              </CourseDetail>
            </Spin>
          </div>
          <div className={styles.right}>
            <CoursesList onChange={handleChangeClass} data={classes} classId={classId} />
          </div>
        </>
      )}
    </div>
  );
};

// 作业
const Works = () => {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<any[]>([]);
  const pageSize = 25;
  const [total, setTotal] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const history = useHistory();

  const { data: classData } = useRequest(() =>
    allGet({ params: { mod: 'busywork', do: 'mycourse', version: 'pc1.0' } }),
  );
  const newClassData = Array.isArray(classData)
    ? [{ name: '全部', classid: -9999 }, ...classData]
    : [{ name: '全部', classid: -9999 }];

  const getData = async () => {
    setLoading(true);
    console.log(filterStatus, 'filterStatus');
    const params = {
      mod: 'busywork',
      do: 'my',
      version: 'pc1.0',
      page: currentPage,
      perpage: pageSize,
      classid: classId.current,
      score: filterStatus === 0 ? 'unscore' : filterStatus === 'all' ? 'scored' : filterStatus,
    };
    const response = await allGet({ params });
    if (response.success) {
      setData(
        response.data?.list?.map((item) => ({ ...item, type: item.videoid ? 'video' : 'img' })) ||
          [],
      );
      setTotal(response.data.count || 0);
    }

    //  setData(mockData(1, 25, 200, 200, [{ type: 'img' }, { type: 'video' }]))
    setLoading(false);
  };
  const [filterStatus, setFilterStatus] = useState<any>(0);
  const handlePageChange = (page: number, pageSize: number) => {
    setCurrentPage(page);
  };
  useEffect(() => {
    getData();
  }, [filterStatus, currentPage]);
  const scores = [
    { label: '全部', value: 'all' },
    { label: 'S', value: 'S' },
    { label: 'A+', value: 'A+' },
    { label: 'A', value: 'A' },
    { label: 'B', value: 'B' },
  ];

  const classId = useRef();
  const handleSelectChange = async (value: any) => {
    classId.current = value === -9999 ? undefined : value;
    getData();
  };

  const handleFilterChange = async (value: any) => {
    setFilterStatus(value);
  };

  const handleWorksItemClick = (index) => {
    // console.log(data[index], 2222);
    // if (data[index].videoid && !data[index].video) {
    //   return message.warning({ content: '视频正在转码，请稍后来查看' });
    // }

    VideoPlayerModal.showListWithDetail({
      showDownLoadWorkFile: true,
      data: data.map((item) => ({ ...item, url: item.video || item.pic })),
      defaultIndex: index,
    });
  };
  const handleWorksItemEditClick = (index) => {
    const item = data[index];
    const redirect = window.encodeURIComponent('/learning?index=2');
    // window.location.href = `/center/upload/work?lid=${item?.lid}&bid=${item?.bid}&redirect=${redirect}`;
    history.push(
      `/center/upload/work?lid=${item?.lid}&bid=${item?.bid}&redirect=${redirect}&classid=${item.classid}`,
    );
  };
  return (
    <div className={styles.works}>
      <Spin spinning={loading}>
        <div className={styles.header}>
          <div className={styles.oreders}>
            <div
              className={classNames(styles.orderItem, { [styles.actived]: filterStatus === 0 })}
              onClick={() => handleFilterChange(0)}
            >
              未评分
            </div>
            <div
              className={classNames(styles.orderItem, {
                [styles.actived]: scores.some((item) => item.value === filterStatus),
              })}
              style={{ cursor: 'inherit' }}
            >
              已评分{' '}
              {scores.map((item) => {
                return (
                  <div
                    key={item.value}
                    className={classNames(styles.item, {
                      [styles.actived]: item.value === filterStatus,
                    })}
                    onClick={() => handleFilterChange(item.value)}
                  >
                    {item.label}
                  </div>
                );
              })}
            </div>
          </div>

          <div className={styles.selectWrapper}>
            课程：
            <Select
              placeholder="请选择课程"
              className={styles.select}
              onChange={handleSelectChange}
              defaultValue={-9999}
            >
              {newClassData?.map((item) => {
                return (
                  <Select.Option key={item.classid} value={item.classid}>
                    {item.name}
                  </Select.Option>
                );
              })}
            </Select>
          </div>
        </div>
        <div className={styles.main}>
          {loading ? null : data.length > 0 ? (
            <div className={styles.list}>
              {data.map((item, index) => (
                <div key={item.bid} className={styles.item}>
                  {' '}
                  <WorksItem
                    isLink={false}
                    onClick={handleWorksItemClick}
                    onEdit={handleWorksItemEditClick}
                    itemType={filterStatus === 0 ? 5 : 6}
                    type={item.type}
                    index={index}
                    {...item}
                  />
                </div>
              ))}
            </div>
          ) : (
            <Empty style={{ margin: '100px auto 0 auto' }} />
          )}
        </div>
        {total > pageSize && (
          <Pagination
            pageSize={pageSize}
            className={styles.pagination}
            onChange={handlePageChange}
            total={total}
            current={currentPage}
          />
        )}
      </Spin>
    </div>
  );
};

//合同
const Contract = () => {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<any>({});
  const [current, setCurrent] = useState(1);
  const [filterStatus, setFilterStatus] = useState<any>(1);
  const pageSize = 15;
  const init = async () => {
    setLoading(true);
    const response = await allGet({
      params: {
        mod: 'contract',
        do: 'list',
        version: 'pc1.0',
        page: current,
        perpage: pageSize,
        status: filterStatus,
      },
    });
    setData(response);

    setLoading(false);
  };
  useEffect(() => {
    init();
  }, [current, filterStatus]);

  const handlePageChange = (page: number, pageSize: number) => {
    setCurrent(page);
  };
  const handleFilterStatusChange = (value) => {
    setCurrent(1);
    setFilterStatus(value);
  };
  const handleSign = async (classid) => {
    const response = await allGet({
      params: { mod: 'contract', do: 'begin', version: 'pc1.0', classid },
    });
    if (!response.success) return;

    window.location.href = response?.data;
  };

  const handleDownload = (item) => {
    downLoad(item.usercontract2, { fileName: item.classname + '.pdf' });
  };
  return (
    <div className={styles.contract}>
      <Spin spinning={loading}>
        <div className={styles.header}>
          <div
            className={classNames(styles.filter, { [styles.actived]: filterStatus === 1 })}
            onClick={() => handleFilterStatusChange(1)}
          >
            未签署
          </div>
          <div
            className={classNames(styles.filter, { [styles.actived]: filterStatus === 2 })}
            onClick={() => handleFilterStatusChange(2)}
          >
            已签署
          </div>
        </div>
        <div className={styles.list}>
          {data?.data?.list?.length > 0 ? (
            data?.data?.list?.map?.((item, index) => {
              return (
                <div className={styles.item} key={item.eid}>
                  <div className={styles.main}>
                    <div className={styles.body}>
                      <div className={styles.left}>
                        <div className={styles.ratio}>
                          <div className={styles.content}>
                            <img
                              loading="lazy"
                              className={styles.img}
                              src={item?.course?.thumb}
                              alt=""
                            />
                          </div>
                        </div>
                      </div>
                      <div className={styles.right}>
                        <div className={styles.title}>{item.classname}</div>
                        <div className={styles.time}>{item?.payline}</div>
                        <div className={styles.info}>
                          <div className={styles.priceWrapper}>
                            <div className={styles.filed}>
                              <span className={styles.key}>实付：</span>¥{item.payed}
                            </div>
                            <i className={styles.line} />
                            <div className={styles.filed}>
                              <span className={styles.key}>发票金额：</span>
                              <strong>¥{item.payed}</strong>
                            </div>
                          </div>
                          <div className={styles.buttons}>
                            {filterStatus == 1 && (
                              <div
                                className={classNames(styles.button, styles.primary)}
                                onClick={() => handleSign(item.classid)}
                              >
                                签署合同
                              </div>
                            )}
                            {filterStatus == 2 && (
                              <>
                                {/* <div className={styles.button} onClick={() => handleDownload(item)}>
                                  下载
                                </div> */}
                                <a
                                  className={classNames(styles.button, styles.primary)}
                                  href={item.usercontract2}
                                  target="_blank"
                                  rel="noreferrer"
                                >
                                  <i className={styles.icon} />
                                  查看
                                </a>
                              </>
                            )}
                          </div>
                        </div>
                      </div>
                    </div>
                    {filterStatus == 1 ? (
                      <div className={styles.footer}>
                        <div className={styles.left}>
                          合同签订完成后才有权限学习。
                          <strong
                            onClick={() =>
                              window.open(
                                'https://www.cgjoy.com/forum.php?mod=viewthread&tid=111599&page=1&extra=#pid3651806',
                              )
                            }
                          >
                            如何签署培训合同？
                          </strong>
                        </div>
                        <div className={styles.status}>未签署</div>
                      </div>
                    ) : (
                      <div className={styles.footer}>
                        <div className={styles.left}>合同签订已完成，可前往学习。</div>
                        <div className={classNames(styles.status, styles.green)}>签署成功</div>
                      </div>
                    )}
                  </div>
                </div>
              );
            })
          ) : (
            <Empty style={{ margin: '100px auto 0 auto' }} />
          )}
        </div>
        {data?.data?.count > pageSize && (
          <Pagination
            pageSize={pageSize}
            className={styles.pagination}
            onChange={handlePageChange}
            total={data?.data?.count}
            current={current}
          />
        )}
      </Spin>
    </div>
  );
};
//发票
const Invoice = () => {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<any>([]);
  const [current, setCurrent] = useState(1);
  const [filterStatus, setFilterStatus] = useState<any>(-1);

  const pageSize = 15;
  const init = async () => {
    setLoading(true);
    const response = await allGet({
      params: {
        mod: 'invoice',
        do: 'all',
        version: 'pc1.0',
        page: current,
        perpage: pageSize,
        status: filterStatus,
      },
    });
    setData(response);

    setLoading(false);
  };
  useEffect(() => {
    init();
  }, [current, filterStatus]);
  const handlePageChange = (page: number, pageSize: number) => {
    setCurrent(page);
  };
  const handleFilterStatusChange = (value) => {
    setCurrent(1);
    setFilterStatus(value);
  };

  const handleInvoice = (item) => {
    InvoiceModal.show({
      data: item,
      onSuccess: async (values) => {
        const params: any = {
          mod: 'invoice',
          do: 'add',
          version: 'pc1.0',
          classid: item.classid,
          addsubmit: 1,
          type: values.invoiceType,
          nametype: values.nameType,
          email: values.email,
        };

        // 根据 nameType 值决定发送哪些参数
        if (values.nameType === '0') {
          // 企业类型发票需要的参数
          params.invoicename = values.invoicename;
          params.invoiceid = values.invoiceid;
          params.address = values.address;
          params.mobile = values.mobile;
          params.bank = values.bank;
          params.bankaccount = values.bankaccount;
        } else if (values.nameType === '1') {
          // 个人类型发票需要的参数
          params.invoicename = values.invoicename;
          params.invoiceid = values.invoiceid;
        }

        const response = await allPost({
          data: params,
        });
        if (response.success) {
          init();
          return message.success('提交成功，等待审核');
        }
        if (!response.success) {
          return message.success(response.data || '提交失败');
        }
        return false;
      },
    });
  };
  return (
    <div className={styles.invoice}>
      <Spin spinning={loading}>
        <div className={styles.header}>
          <div
            className={classNames(styles.filter, { [styles.actived]: filterStatus === -1 })}
            onClick={() => handleFilterStatusChange(-1)}
          >
            可开发票
          </div>
          <div
            className={classNames(styles.filter, { [styles.actived]: filterStatus === 0 })}
            onClick={() => handleFilterStatusChange(0)}
          >
            开具中
          </div>
          <div
            className={classNames(styles.filter, { [styles.actived]: filterStatus === 1 })}
            onClick={() => handleFilterStatusChange(1)}
          >
            已开具
          </div>
        </div>
        <div className={styles.list}>
          {data?.data?.list?.length > 0 ? (
            data?.data?.list?.map?.((item, index) => {
              return (
                <div className={styles.item} key={item.orderno}>
                  <div className={styles.main}>
                    <div className={styles.body}>
                      <div className={styles.left}>
                        <div className={styles.ratio}>
                          <div className={styles.content}>
                            <img loading="lazy" className={styles.img} src={item.thumb} alt="" />
                          </div>
                        </div>
                      </div>
                      <div className={styles.right}>
                        <div className={styles.title}>{item.coursename}</div>
                        {item.status == 0 ? (
                          <div className={styles.applying}>
                            审核中
                            <i className={styles.line} />
                            从申请之日起，三个工作日内
                          </div>
                        ) : (
                          <div className={styles.time}>{item.payline}</div>
                        )}
                        <div className={styles.info}>
                          <div className={styles.priceWrapper}>
                            <div className={styles.filed}>
                              <span className={styles.key}>实付：</span>¥{item.payed}
                            </div>
                            <i className={styles.line} />
                            <div className={styles.filed}>
                              <span className={styles.key}>发票金额：</span>
                              <strong>¥{item.payed}</strong>
                            </div>
                          </div>
                          <div className={styles.buttons}>
                            {item.status == -1 && (
                              <div
                                className={classNames(styles.button, styles.primary)}
                                onClick={() => handleInvoice(item)}
                              >
                                申请发票
                              </div>
                            )}
                            {item.status == 0 && (
                              <div
                                className={classNames(
                                  styles.button,
                                  styles.primary,
                                  styles.yellows,
                                )}
                                onClick={() => handleInvoice(item)}
                              >
                                修改发票
                              </div>
                            )}
                          </div>
                        </div>
                      </div>
                    </div>
                    {item.status != -1 && (
                      <div className={styles.footer}>
                        <div className={styles.left}>
                          <div className={styles.filed}>
                            <span className={styles.key}>发票抬头：</span>{' '}
                            <span className={styles.value}>{item.invoicename}</span>
                          </div>
                          <div className={styles.filed}>
                            <span className={styles.key}>发票发至邮箱：</span>
                            <span className={styles.value}>{item.email}</span>
                          </div>
                        </div>
                        {item.status == 1 && (
                          <div className={classNames(styles.status, styles.green)}>
                            <i className={styles.icongou} />
                            已开具
                          </div>
                        )}
                      </div>
                    )}
                  </div>
                </div>
              );
            })
          ) : (
            <Empty style={{ margin: '100px auto 0 auto' }} />
          )}
        </div>
        {data?.count > pageSize && (
          <Pagination
            pageSize={pageSize}
            className={styles.pagination}
            onChange={handlePageChange}
            total={data?.count}
            current={current}
          />
        )}
      </Spin>
    </div>
  );
};

const Index = () => {
  const onChange = (key: string) => {
    console.log(key);
  };
  const { index = 1, classid } = (useHistory().location as any)?.query;
  return (
    <div className={styles.page}>
      <Tabs className={styles.mytab} defaultActiveKey={index} onChange={onChange}>
        <TabPane tab="我的课程" key="1">
          <Courses classid={classid} />
        </TabPane>
        {/* <TabPane tab="我的作业" key="2">
          <Works />
        </TabPane> */}
        <TabPane tab="合同签订" key="3">
          <Contract />
        </TabPane>
        <TabPane tab="发票管理" key="4">
          <Invoice />
        </TabPane>
      </Tabs>
    </div>
  );
};

export default Index;
